<?php
require_once dirname(__FILE__) . '/../plugin/phpexcel/Classes/PHPExcel.php';
require_once dirname(__FILE__) . '/../plugin/phpexcel/Classes/PHPExcel/Writer/Excel2007.php';

//返回当前的脚本名
function self_name()
{
  return ltrim(strrchr($_SERVER['PHP_SELF'], "/"), "/");
}
// 获取后缀名
function get_file_ext($s = '')
{
  return ltrim(strrchr($s, "."), ".");
}
// 获取文件名
function get_file_name($s = '')
{
  return strpos($s, '.') !== false ? substr($s, 0, strrpos($s, ".")) : $s;
}

// 文件绝对路径转相对路径
function handle_cont($s = '')
{
  $pattern = "/(\/[0-9a-z]+)?\/uploadfile/i";
  return SITE_SUB ? $s : preg_replace($pattern, 'uploadfile', $s);
}


function dir_url($path, $dir = 'static')  // Absolute File path or Directory path to WebURL
{
  $path = str_replace(DIRECTORY_SEPARATOR, '/', $path); // 将DIRECTORY_SEPARATOR都替换为/，便于统一处理
  list($pre, $url) = explode('static', $path);
  return '/' . $dir . $url;
}

// 替换默认图片
function img_always($s = '')
{
  if (empty($s)) {
    return '//picsum.photos/400';
  }
  $pattern = "/(\/[0-9a-z]+)?\/uploadfile/i";
  return SITE_SUB ? $s : preg_replace($pattern, '/uploadfile', $s);
}

// 判断目录是否存在不存在则创建
function mk_dir($dir, $mode = 0777)
{
  if (is_dir($dir)) {
    return TRUE;
  }
  return @mkdir($dir, $mode);
}

function file_it($str, $dir, $name, $ex = false)
{
  ini_set("set_time_limit", 0);

  $str = str_replace('\\', '', $str);

  if ($dir == '/') {
    $file = ROOT_PATH . $name;
  } elseif (strpos($dir, '/') !== false) {
    $dir = rtrim($dir, '/');
    $file = $dir . DIRECTORY_SEPARATOR . $name;
    if (!is_dir($dir)) {
      if (mk_dir($dir) === false) {
        alert_back($GLOBALS['lang']['mkdir_error']);
      }
    }
  } else {
    $path = ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . $dir;
    $file = $path . DIRECTORY_SEPARATOR . $name . '.' . $dir;
    if (!is_dir($path)) {
      if (mk_dir($path) === false) {
        alert_back($GLOBALS['lang']['mkdir_error']);
      }
    }
  }

  if ($ex && file_exists($file)) {
    $fp = fopen($file, 'a');
  } else {
    $fp = fopen($file, 'w');
  }

  fwrite($fp, $str);
  fclose($fp);

  return true;
}

function file_get($dir, $name)
{
  $file = strpos($dir, '/') !== false
    ? $dir . DIRECTORY_SEPARATOR . $name
    : ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $name . '.' . $dir;

  if (is_file($file)) {
    return $dir == 'json' ? stripslashes_deep(json_decode(file_get_contents($file), true)) : file_get_contents($file);
  }

  return false;
}

function file_delete($dir, $name)
{
  $file = strpos($dir, '/') !== false
    ? $dir . DIRECTORY_SEPARATOR . $name
    : ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $name . '.' . $dir;

  if (is_file($file)) {
    return @unlink($file);
  }

  return false;
}

function get_content_images($html = '')
{
  // $html = '<p> <img src="/uploadfile/image/20200518/20200518105839_86554.jpg" alt=""> </p> <p> <img src="/uploadfile/image/20200518/20200518105849_30920.jpg" alt=""> </p> <p> <img src="/uploadfile/image/20200518/20200518105858_26269.jpg" alt=""> </p>';

  if (empty($html)) {
    return false;
  }

  $regx = "/\/uploadfile\/image\/[a-z0-9\.\_\/]*/i";
  preg_match_all($regx, $html, $arr);
  return $arr[0];
}

/**
 * csv_export function
 *
 * @param [type] $data
 * @param array $titleList
 * @param array $dataList 有多余数据时通过这个数组限制
 * @param string $fileName
 * @return csv file path
 */
function csv_export($data, $titleList = [], $dataList = [], $fileName = '')
{
  ini_set("set_time_limit", 0);
  ini_set("max_execution_time", "3600");

  $dir = ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . 'csv';

  if (!is_dir($dir)) {
    if (mk_dir($dir) === false) {
      alert_back($GLOBALS['lang']['mkdir_error']);
    }
  }

  $fileName = empty($fileName) ? date('YmdHis', gmtime()) : $fileName;
  $filePath = $dir . DIRECTORY_SEPARATOR . $fileName . '.csv';

  $fp = fopen($filePath, 'w');
  fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //转码,防止乱码
  fputcsv($fp, $titleList);

  if (empty($dataList)) {
    foreach ($data as $val) {
      fputcsv($fp, $val);
    }
  } else {
    foreach ($data as $val) {
      $arr = array();
      for ($i = 0; $i < count($dataList); $i++) {
        $arr[] = $val[$dataList[$i]];
      }
      fputcsv($fp, $arr);
    }
  }

  fclose($fp);

  return dir_url($filePath);
}

function excel_export($data, $titleList = [], $dataList = [], $fileName = '')
{
  ini_set("set_time_limit", 0);
  ini_set("max_execution_time", "3600");

  $dir = ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . 'csv';

  if (!is_dir($dir)) {
    if (mk_dir($dir) === false) {
      alert_back($GLOBALS['lang']['mkdir_error']);
    }
  }

  $fileName = empty($fileName) ? date('YmdHis', gmtime()) : $fileName;
  $filePath = $dir . DIRECTORY_SEPARATOR . $fileName . '.xls';

  header("Content-type:application/vnd.ms-excel");
  header("Content-Disposition:attachment;filename=$fileName");

  $tab = "\t";
  $br = "\n";

  $fp = fopen($filePath, 'w');
  fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //转码,防止乱码
  fputcsv($fp, $titleList, $tab);

  if (empty($dataList)) {
    foreach ($data as $val) {
      fputcsv($fp, $val, $tab);
    }
  } else {
    foreach ($data as $val) {
      $arr = array();
      for ($i = 0; $i < count($dataList); $i++) {
        $arr[] = $val[$dataList[$i]];
      }
      fputcsv($fp, $arr, $tab);
    }
  }

  fclose($fp);

  return dir_url($filePath);
}

function xls_export($data, $titleList = [], $dataList = [], $fileName = '', $cellWidth = [])
{
  ini_set("set_time_limit", 0);
  ini_set("max_execution_time", "3600");

  $dir = ROOT_PATH . 'static' . DIRECTORY_SEPARATOR . 'csv';

  if (!is_dir($dir)) {
    if (mk_dir($dir) === false) {
      alert_back($GLOBALS['lang']['mkdir_error']);
    }
  }

  $fileName = empty($fileName) ? date('YmdHis', gmtime()) : $fileName;
  $filePath = $dir . DIRECTORY_SEPARATOR . $fileName . '.xlsx';

  // Create new PHPExcel object
  $objPHPExcel = new PHPExcel();
  // $objPHPExcel->getProperties()->setCreator("作者")
  //   ->setLastModifiedBy("作者")
  //   ->setTitle('标题')
  //   ->setSubject('主题')
  //   ->setDescription('描述')
  //   ->setKeywords("excel")
  //   ->setCategory("result file");
  $active_sheet = $objPHPExcel->setActiveSheetIndex(0);

  // title
  foreach ($titleList as $key => $title) {
    $active_sheet->setCellValue(num_alph($key) . '1', $title);
    if (empty($cellWidth)) continue;
    $active_sheet->getColumnDimension(num_alph($key))->setWidth($cellWidth[$key]);
  }

  // Miscellaneous glyphs, UTF-8
  if (empty($dataList)) {
    $active_sheet->fromArray($data, null, 'A' . ($key + 2));
  } else {
    foreach ($data as $key => $val) {
      $arr = array();
      for ($i = 0; $i < count($dataList); $i++) {
        $arr[] = str_replace('#', '', $val[$dataList[$i]]);
      }
      $active_sheet->fromArray($arr, null, 'A' . ($key + 2));
    }
  }

  // Rename worksheet
  $active_sheet->setTitle($fileName);

  // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  $objPHPExcel->setActiveSheetIndex(0);

  $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
  $objWriter->save($filePath); //保存成功

  return dir_url($filePath);
}